import React, { Component } from 'react'
import { View, Image, Text, ScrollView,Button } from '@tarojs/components'
import { getLocation, downloadFile ,pageScrollTo,saveImageToPhotosAlbum, getCurrentInstance} from '@tarojs/taro'
import { AtDrawer ,AtFloatLayout} from 'taro-ui'
import {
  GET_TIAN_QI,
  GET_TIAN_QI_NOW,
  GET_DAY_CALENDAR,
  GET_DAY_CALENDAR_EX,
  GET_DAY_CALENDAR_HOUR,
  GET_DAY_ONE_WORD,
  GET_SUGGEST,
  formatTime
} from '../../api'
import { getLunarDate } from '../../api/calendar'
import "taro-ui/dist/style/components/button.scss" // 按需引入
import './index.scss'
import icon from "../../assets/icon_live.png"
import bgcImg from "../../assets/bgc.jpg"
import shareImg from "../../assets/share.png"

import day15Icon from "../../assets/icon_date.png"
import { iconClass, imgCode, liveCode } from '../../api/iconClass'
import { closeLoading, loading, successTip, warning } from '../../api/tips'
// import { EChart } from "echarts-taro3-react";


// const barChart = React.createRef();
export default class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      showDayPage: false,
      isOpened:false,
      d: {},
      shareData:{},
      filePath: null,
      weatherNow: {},
      suggestList: [],
      days: [],
      hourly: [],
      maxArr: [],
      minArr: [],
      maxArr_max: null,
      maxArr_min: null,
      minArr_max: null,
      minArr_min: null,
    }
  }
  openShare(){
    this.setState({
      isOpened:true,
    })
  }
  handleClose() {
    this.setState({
      isOpened: false
    })
  }
  saveImg(){
    console.log(this.state.shareData);
    loading('正在保存')
    downloadFile({
      url:  this.state.shareData.shareImage, //仅为示例，并非真实的资源
      success (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          loading('保存中...')
          
          let url= res.tempFilePath
          saveImageToPhotosAlbum({
            filePath:url,
            success(res) {
              console.log('res', res);
              successTip('已保存到相册')
             
            },
            fail(err) {
              closeLoading()
              warning('保存失败')
            }
          })
        }else{
          closeLoading()
          warning('保存失败')
        }
      },
      fail(err) {
        closeLoading()
        warning('保存失败')
      }
    })

   
  }
  getLocation() {
    getLocation({
      type: 'wgs84',
      success: (res) => {
        let location = {
          latitude: res.latitude,
          longitude: res.longitude
        }
        this.getTianQiDays(location)
        this.getTianQiTimes(location)
        this.theSuggest(location)
      }
    })
  }
  getTianQiDays(data) {
    GET_TIAN_QI(data).then(res => {
      // console.log(res);
      if (res.code == '000000') {
        let days = res.data
        this.initDays(days)
        this.setState({
          days
        })
      }
    })
  }
  getTianQiTimes(data) {
    GET_TIAN_QI_NOW(data).then(res => {
      if (res.code == '000000') {
        let weatherNow = res.data
        let hourly = weatherNow.hourly
        let pic = weatherNow.pic

        this.setState({
          weatherNow,
          hourly
        })
        if (pic)
          downloadFile({
            url: pic, //仅为示例，并非真实的资源
            success: (res) => {
              // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
                this.setState({
                  filePath: res.tempFilePath
                })

              }
            }
          })
      }
    })
  }
  initDays(days) {
    let maxArr = [],
      minArr = [],
      maxArr_max,
      maxArr_min,
      minArr_max,
      minArr_min
    days.forEach(item => {
      maxArr.push(item.highTemperature)
      minArr.push(item.lowTemperature)
    })
    maxArr_max = Math.max(...maxArr)
    maxArr_min = Math.min(...maxArr)
    minArr_max = Math.max(...minArr)
    minArr_min = Math.min(...minArr)
    this.setState({
      maxArr,
      minArr,
      maxArr_max,
      maxArr_min,
      minArr_max,
      minArr_min
    })
  }
  componentDidMount() {
    this.get_autocode()
    setTimeout(() => {
    this.getLocation()
    this.getToday()

    }, 10000);

  }
  getToday() {
    GET_DAY_CALENDAR().then(res => {
      console.log(res);
      if (res.code == '000000') {
        let d = res.data
        d.today = formatTime(new Date())
        d.days = new Date().getDate()
        this.setState({
          d
        })
      }
    })
    GET_DAY_ONE_WORD().then(res => {
      console.log(res);
      if (res.code == '000000') {
        let shareData = res.data
        this.setState({
          shareData
        })
        // this.getSysInfo()
      }
    })
  }
  theSuggest(data) {
    GET_SUGGEST(data).then(res => {
      console.log(res);
      if (res.code == '000000') {
        let suggestList = res.data
        this.setState({
          suggestList
        })
      }
    })
  }

  onShareAppMessage(res) {
    return {
      title: '今日天气',
      path: '/pages/index/index'
    }
  }
  onPageScroll(e) { // 页面滚动监听
    console.log(e.scrollTop);
    if (e.scrollTop < -150) {
      this.setState({
        showDayPage: true
      })
    }else if(e.scrollTop>0){
      if(100>e.scrollTop&&this.state.showDayPage){
          pageScrollTo({
            scrollTop: 0,
            duration: 500
          })
      }else{
        if(this.state.showDayPage){
          this.setState({
            showDayPage: false
          })
        }
      }
    }

  }
  toTop() {
    this.setState({
      showDayPage: false
    })
  }
  get_autocode() {
    let params = getCurrentInstance().router.params
    if(params.showDayPage){
      setTimeout(() => {
        this.setState({
          showDayPage:true
        })
      }, 0);
    }
   
   
  }
  onShareAppMessage(options) {
    
    if (options.from == "button") {
      
      
      return {
        //## 此为转发页面所显示的标题
        title: `${ this.state.shareData.translation}`,
        path: `/pages/index/index?showDayPage=true`,
        imageUrl: this.state.shareData.shareImage,
        success: function (res) {
        },
        //## 转发操作失败/取消 后的回调处理，一般是个提示语句即可
        fail: function (err) {
          // util.showToast(0, '朋友代付转发失败...');
        }
      }
    }

  }



  render() {
    // console.log(iconClass,'---iconClass');
    // let types = this.state.types,
    let weatherNow = this.state.weatherNow,
      bgc = `background:rgba(0,0,0,0.2)`,
      // bgc2 = `background:${types.day.color2}`,
      days = this.state.days,
      d = this.state.d,
      hourly = this.state.hourly,
      filePath = this.state.filePath,

      showDayPage = this.state.showDayPage,
      shareData = this.state.shareData,
      // minArr = this.state.minArr,
      maxArr_max = this.state.maxArr_max,
      maxArr_min = this.state.maxArr_min,
      minArr_max = this.state.minArr_max,
      minArr_min = this.state.minArr_min,
      suggestList = this.state.suggestList,
      isOpened=this.state.isOpened
    // console.log(maxArr_max,maxArr_min,minArr_max,minArr_min);
    let w = 170, h = 80;
    let line = (item, nextItem) => {
      // console.log(item, nextItem);
      let x1 = w / 2,
        y1 = (h / (maxArr_max - maxArr_min)) * (item.highTemperature - maxArr_min),
        x2 = w / 2 + w,
        y2 = (h / (maxArr_max - maxArr_min)) * (nextItem.highTemperature - maxArr_min)
      // console.log(x1,x2,y1,y2);
      var lx = x2 - x1;
      var ly = y2 - y1;
      //计算连线长度
      var length = Math.sqrt(lx * lx + ly * ly);
      //弧度值转换为角度值
      var c = 360 * Math.atan2(ly, lx) / (2 * Math.PI);
      //连线中心坐标
      var midX = (x2 + x1) / 2;
      var midY = (y2 + y1) / 2
      var deg = c <= -90 ? (360 + c) : c;
      let lineStyle = `bottom:${midY}rpx;left:${midX - length / 2}rpx;width:${length}rpx;transform:rotate(${-deg}deg);`
      return (
        <View className="maxLine" style={lineStyle}></View>

      )
    }
    let minLine = (item, nextItem) => {
      let x1 = w / 2,
        y1 = (h / (minArr_max - minArr_min)) * (item.lowTemperature - minArr_min),
        x2 = w / 2 + w,
        y2 = (h / (minArr_max - minArr_min)) * (nextItem.lowTemperature - minArr_min)
      var lx = x2 - x1;
      var ly = y2 - y1;
      //计算连线长度
      var length = Math.sqrt(lx * lx + ly * ly);
      //弧度值转换为角度值
      var c = 360 * Math.atan2(ly, lx) / (2 * Math.PI);
      //连线中心坐标
      var midX = (x2 + x1) / 2;
      var midY = (y2 + y1) / 2
      var deg = c <= -90 ? (360 + c) : c;
      let lineStyle = `bottom:${midY}rpx;left:${midX - length / 2}rpx;width:${length}rpx;transform:rotate(${-deg}deg);`
      // console.log(lineStyle);
      return (
        <View className="minLine" style={lineStyle}></View>

      )
    }
    let row = [],
      rowPage = []
    suggestList.forEach((item, index) => {
      let itemContent = (
        <View className="w50 flex1 flexItem">
          <View className="futureIcon">
            <Image className="futureIconSize" mode="aspectFit" src={liveCode[item.type] ? liveCode[item.type] : liveCode['1']}></Image>
            {/* <Image src={liveCode} className="futureIconSize" mode="aspectFit"></Image> */}
          </View>
          <View className="futureText">
            <View>{item.name}</View>
            <View>{item.suggestion}</View>
          </View>
        </View>
      )

      row.push(itemContent)
      if (row.length >= 2 || index == suggestList.length - 1) {
        rowPage.push(
          <View className="flexItem row ">
            {row}
          </View>
        )
        row = []
      }
      // if (index == suggestList.length - 1) {
      //   return rowPage
      // }
    })
    // let theTop = `top:${showDayPage ? '0' : '-110%'}`
    let theTop = `top:${showDayPage ? '' : '-110%'}`
    let pTop=`padding-top:${showDayPage ? '100vh' : '0'};transition: all 0.5s;`
    let dayPageStyle=`top:${showDayPage ? '0' : '-110%'}`
    return (
      <View style={pTop} className="homePage">
        <Image className="bgcImg" src={filePath ? filePath : bgcImg} mode="aspectFill"></Image>
        {/* style={theTop} */}
        <View className='everyDayBgc' style={dayPageStyle}>
        <Image className="codeImg" src={shareData.image} mode="aspectFill"></Image>
          <View className='toTop' onClick={() => this.toTop()}> 收起 ^ </View>
          <View className='everyDay' style={theTop}>
            <View className='td'>{d.days} <Text className='wdays'>{d.weekday}</Text></View>
            <View>{d.lunar}  {d.holiday}</View>
            <View>{d.lunarYear}属{d.animalsYear}</View>
          </View>
          <View className='niceWord' style={theTop}>
          {shareData.translation}
          </View>
          <View className='shareImg'  onClick={()=>this.openShare()}>
          <Image className="shareImage" src={shareImg} mode="aspectFill"></Image>
          </View>
         
        </View>
        <AtFloatLayout isOpened={isOpened} scrollWithAnimation onClose={() => this.handleClose()}>
          {/* asdfksafjagfhg */}
          <Button openType='share' className='buttonBar'>分享</Button>
           <Button  className='buttonBar' onClick={()=>this.saveImg()}>生成图片</Button>
          <Button  className='buttonBar' onClick={() => this.handleClose()}>取消</Button>
        </AtFloatLayout>
        
        <View className='home'>
          <View className="theDay">
            {/* <View></View> */}
            <View>{d.today}</View>
            <View> {d.lunarYear}{d.lunar}</View>
            <View> {d.weekday}</View>
            {/* <Text className="iconfont icon-baoyu"></Text> */}
          </View>
          <View className="tqi">
            <View className="wd ">

              {weatherNow.temperature ? <Text className="num">{weatherNow.temperature}</Text> : ''}
              {/* <Text className="unit">°</Text> */}
            </View>
            <View className="tqName"> {weatherNow.city}  {weatherNow.weather}</View>
          </View>
          <View className="contents">
            {
              // hourly&hourly.length>0?
              <View className="tqiTimes" style={bgc}>
                <ScrollView scrollX className="scrollBar">
                  {
                    hourly.map(item => {
                      return (
                        <View className="inblock " style="padding-top:20rpx">
                          <View className="blockOne">{item.time}</View>
                          <View className="iconImg flexCenter">
                            {/* <Text className={`iconfont ${iconClass[item.weather]?iconClass[item.weather]:'icon-qing'}`}></Text> */}
                            <Image className="imgSize" mode="aspectFit" src={imgCode[item.code] ? imgCode[item.code] : imgCode['99']}></Image>
                          </View>
                          <View className="blockOne">{item.temperature}°</View>
                        </View>
                      )
                    })
                  }
                </ScrollView>
              </View>
              // :''
            }

            {days && days.length ? <View className="future" style={bgc}>
              <View className="futureContent" >
                <View className="day15 flexItem">
                  <Image src={day15Icon} className="titleSize" mode="aspectFit"></Image>
                  <Text className="ml">未来一周天气</Text>

                </View>
                <View className="day15Tq">
                  <ScrollView scrollX className="scrollBar">
                    <View className="day15Bar">
                      {
                        days.map((item, index) => {
                          return (
                            <View className="inblock day1Tq theBorder inblock2">
                              <View className="blockOne">{item.weekDay}</View>
                              <View className="blockOne">{item.date ? item.date.substring(5, item.date.length) : '--'}</View>
                              <View className="iconImg flexCenter">
                                {/* <Text className={`iconfont ${iconClass[item.dayWeather]?iconClass[item.dayWeather]:'icon-qing'}`}></Text> */}
                                {/* {item.dayWeather} */}
                                <Image className="imgSize" mode="aspectFit" src={imgCode[item.dayIcon] ? imgCode[item.dayIcon] : imgCode['99']}></Image>
                              </View>
                              <View className="blockOne">{item.highTemperature}°</View>
                              <View className="theMaxBar">
                                {
                                  index < days.length - 1 ? line(item, days[index + 1]) : ''
                                }
                              </View>
                              <View className="theMinBar">
                                {
                                  index < days.length - 1 ? minLine(item, days[index + 1]) : ''
                                }

                              </View>
                              <View className="blockOne ">{item.lowTemperature}°</View>
                              <View className="iconImg flexCenter">
                                {/* {item.nightWeather} */}
                                {/* <Text className={`iconfont ${iconClass[item.nightWeather]?iconClass[item.nightWeather]:'icon-qing'}`}></Text> */}
                                <Image className="imgSize" mode="aspectFit" src={imgCode[item.nightIcon] ? imgCode[item.nightIcon] : imgCode['99']}></Image>
                              </View>
                              <View className="blockOne" style={item.windDirection == '无持续风向'? 'font-size: 26rpx;':'font-size: 32rpx'}>{ item.windDirection == '无持续风向'?item.windDirection:`${item.windDirection}风`}</View>
                              <View className="blockOne">{item.windScale}级</View>

                            </View>
                          )
                        })
                      }
                    </View>



                  </ScrollView>

                </View>


              </View>

            </View> : ''}
            {rowPage && rowPage.length ? <View className="future" style={bgc}>
              <View className="futureContent" >
                <View className="day15 flexItem">
                  <Image src={icon} className="titleSize" mode="aspectFit"></Image>
                  <Text className="ml">生活指数</Text>

                </View>
                <View className="futureList">
                  {rowPage}
                </View>


              </View>

            </View> : ''}
          </View>

        </View>
      </View>
    )
  }
}
